package com.gopay.scheduler.job;

import com.gopay.common.domain.acps.AcctProd;
import com.gopay.common.domain.acps.model.AcctMastBean;
import com.gopay.cron.service.cloud.CloudAccountGenFtpFileService;
import com.gopay.remote.acps.service.AcctTransRemoteService;
import com.gopay.scheduler.GopayBaseJob;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 *  云账户掌合生成FTP文件
 * Created by Lenovo-songfengli on 2017/8/22.
 */
public class CloudAccountGenFtpFileJob extends GopayBaseJob {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("#{webProperties['cloud.accountGenFtp.custIds']}")
    private String custIds;

    @Value("#{webProperties['cloud.accountGenFtp.basePath']}")
    private String basePath;

    @Resource(name = "cloudAccountGenFtpFileService")
    private CloudAccountGenFtpFileService cloudAccountGenFtpFileService;

    @Resource(name = "acctTransRemoteService")
    private AcctTransRemoteService acctTransRemoteService;

    @Override
    public void doJobInternal() {
      try {
          // 获取需要生成对账文件的客户custId
          Set<String> custIdSet = getPlatformCustIds();
          if (custIdSet != null && custIdSet.isEmpty()) {
              logger.info("job end：没有配置需要生成对账文件的custId，job结束");
              return;
          }

          logger.info("需要生成对账文件的custId：" + this.custIds);

          Calendar cal = Calendar.getInstance();
          cal.add(Calendar.DATE, -1);
          String ymd = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());

          for (String custId : custIdSet) {
              List<AcctMastBean> accts = acctTransRemoteService.getAccounts(custId);
              for (AcctMastBean acct : accts) {
                  //1.生成本地文件及上传FTP(普通账户才生成)
                  if (AcctProd.GNST.toString().equals(acct.getProdCodeStr()) || AcctProd.CLOUD.toString().equals(acct.getProdCodeStr())) {
                      logger.info("custId:" + custId + ",acctId:" + acct.getAcctId() + ",acctProd:" + acct.getProdCodeStr());
                      cloudAccountGenFtpFileService.genFile(basePath, ymd, custId, acct.getAcctId(), acct.getProdCodeStr());
                  }
              }

              //2.清除三十天之前的文件
              String deleteFilePath = basePath + custId + File.separator;   //删除文件的路径
              Calendar calendar = Calendar.getInstance();
              calendar.add(Calendar.DATE, -30);
              String rmd = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
              logger.error("开始清除三十天之前的文件,清除的日期为：" + rmd);
              File path = new File(deleteFilePath + rmd);
              deleteFile(path);
          }
          logger.error("生成云账户对账文件,checkDate=" + ymd + ",custId=" + custIds);
      }catch (Exception e){
          logger.error("生成云账户对账文件失败",e);
      }
    }


    private Set<String> getPlatformCustIds() {
        Set<String> set = new HashSet<>();
        if(this.custIds != null && StringUtils.isNotBlank(this.custIds)) {
            if(this.custIds.contains(",")) {
                String[] strArr = this.custIds.split(",");
                for(int i = 0; i < strArr.length; i++) {
                    set.add(strArr[i]);
                }
            } else {
                set.add(this.custIds);
            }
        }
        return set;
    }

    private void deleteFile(File file) {
        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (int i = 0;i < files.length;i ++) {
                    this.deleteFile(files[i]);
                }
                file.delete();//删除文件夹
            }
        }
    }

}
